const { Order, Pet, User, Caregiver, Service } = require('../models');
const { AppError } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 过滤对象，只保留允许的字段
const filterObj = (obj, ...allowedFields) => {
  const newObj = {};
  Object.keys(obj).forEach(el => {
    if (allowedFields.includes(el)) newObj[el] = obj[el];
  });
  return newObj;
};

// 获取公开的可接订单列表（无需登录）
exports.getAvailableOrders = async (req, res, next) => {
  try {
    const { 
      category, 
      location, 
      startDate, 
      endDate, 
      priceMin, 
      priceMax,
      page = 1, 
      limit = 10,
      sort = '-createdAt'
    } = req.query;
    
    // 构建查询条件 - 只显示待确认的订单
    const where = { 
      status: 'pending',
      startDateTime: { [Op.gte]: new Date() } // 只显示未来的订单
    };
    
    // 服务分类过滤
    if (category) {
      const service = await Service.findOne({ where: { category } });
      if (service) {
        where.serviceId = service.id;
      }
    }
    
    // 时间范围过滤
    if (startDate) {
      where.startDateTime = { [Op.gte]: new Date(startDate) };
    }
    if (endDate) {
      where.endDateTime = { [Op.lte]: new Date(endDate) };
    }
    
    // 价格范围过滤 (使用 JSON 字段查询需要特殊处理)
    // 暂时省略价格过滤，后续可以添加
    
    const offset = (page - 1) * limit;
    
    const { count, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'firstName', 'lastName']
        },
        {
          model: Pet,
          as: 'pets',
          attributes: ['id', 'name', 'species', 'breed', 'photos']
        },
        {
          model: Service,
          as: 'service',
          attributes: ['id', 'name', 'category', 'description', 'pricing']
        }
      ],
      order: [[sort.startsWith('-') ? sort.substring(1) : sort, sort.startsWith('-') ? 'DESC' : 'ASC']],
      limit: parseInt(limit),
      offset
    });
    
    // 如果用户已登录，可以提供更多个性化信息
    let personalizedData = {};
    if (req.user) {
      // 可以添加基于用户偏好的推荐逻辑
      personalizedData.isLoggedIn = true;
      personalizedData.userLocation = req.user.address;
    }
    
    res.status(200).json({
      status: 'success',
      results: orders.length,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / limit),
      data: {
        orders,
        ...personalizedData
      }
    });
  } catch (error) {
    logger.error('获取可接订单列表错误:', error);
    return next(new AppError('获取订单列表失败', 500));
  }
};

// 获取当前用户的所有订单
exports.getMyOrders = async (req, res, next) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    
    // 构建查询条件
    const where = { customerId: req.user.id };
    if (status) {
      where.status = status;
    }
    
    const offset = (page - 1) * limit;
    
    const { count, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'firstName', 'lastName', 'email', 'phone']
        },
        {
          model: Caregiver,
          as: 'caregiver',
          include: [{
            model: User,
            as: 'user',
            attributes: ['id', 'firstName', 'lastName']
          }]
        },
        {
          model: Pet,
          as: 'pets',
          attributes: ['id', 'name', 'species', 'breed', 'photos']
        },
        {
          model: Service,
          as: 'service',
          attributes: ['id', 'name', 'category', 'duration', 'pricing']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset
    });
    
    res.status(200).json({
      status: 'success',
      results: orders.length,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / limit),
      data: {
        orders
      }
    });
  } catch (error) {
    logger.error('获取用户订单列表错误:', error);
    return next(new AppError('获取订单列表失败', 500));
  }
};

// 获取护理员的所有订单
exports.getCaregiverOrders = async (req, res, next) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    
    // 查找护理员信息
    const caregiver = await Caregiver.findOne({ where: { userId: req.user.id } });
    if (!caregiver) {
      return next(new AppError('您不是注册的护理员', 403));
    }
    
    // 构建查询条件
    const where = { caregiverId: caregiver.id };
    if (status) {
      where.status = status;
    }
    
    const offset = (page - 1) * limit;
    
    const { count, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'address']
        },
        {
          model: Caregiver,
          as: 'caregiver',
          include: [{
            model: User,
            as: 'user',
            attributes: ['id', 'firstName', 'lastName']
          }]
        },
        {
          model: Pet,
          as: 'pets',
          attributes: ['id', 'name', 'species', 'breed', 'photos', 'health', 'behavior']
        },
        {
          model: Service,
          as: 'service',
          attributes: ['id', 'name', 'category', 'duration', 'pricing']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset
    });
    
    res.status(200).json({
      status: 'success',
      results: orders.length,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / limit),
      data: {
        orders
      }
    });
  } catch (error) {
    logger.error('获取护理员订单列表错误:', error);
    return next(new AppError('获取订单列表失败', 500));
  }
};

// 获取所有订单（管理员功能）
exports.getAllOrders = async (req, res, next) => {
  try {
    const where = {};
    
    // 状态过滤
    if (req.query.status) {
      where.status = req.query.status;
    }
    
    // 分页
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    // 排序
    const order = [];
    if (req.query.sort) {
      const sortFields = req.query.sort.split(',');
      sortFields.forEach(field => {
        if (field.startsWith('-')) {
          order.push([field.substring(1), 'DESC']);
        } else {
          order.push([field, 'ASC']);
        }
      });
    } else {
      order.push(['createdAt', 'DESC']);
    }
    
    const { count, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'firstName', 'lastName', 'email']
        },
        {
          model: Caregiver,
          as: 'caregiver',
          include: [{
            model: User,
            as: 'user',
            attributes: ['id', 'firstName', 'lastName']
          }]
        },
        {
          model: Pet,
          as: 'pets',
          attributes: ['id', 'name', 'species', 'breed']
        },
        {
          model: Service,
          as: 'service',
          attributes: ['id', 'name', 'category']
        }
      ],
      order,
      limit,
      offset
    });
    
    res.status(200).json({
      status: 'success',
      results: orders.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        orders
      }
    });
  } catch (error) {
    logger.error('获取订单列表错误:', error);
    return next(new AppError('获取订单列表失败', 500));
  }
};

// 获取单个订单信息
exports.getOrder = async (req, res, next) => {
  try {
    const order = await Order.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'address']
        },
        {
          model: Caregiver,
          as: 'caregiver',
          include: [{
            model: User,
            as: 'user',
            attributes: ['id', 'firstName', 'lastName']
          }]
        },
        {
          model: Pet,
          as: 'pets',
          attributes: ['id', 'name', 'species', 'breed', 'photos', 'health', 'behavior', 'feeding', 'careNeeds']
        },
        {
          model: Service,
          as: 'service',
          attributes: ['id', 'name', 'category', 'description', 'duration', 'pricing', 'requirements']
        }
      ]
    });
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    // 检查权限：只有订单相关用户、护理员或管理员可以查看
    const isCustomer = order.customerId === req.user.id;
    const isCaregiver = order.caregiverId && order.caregiver && order.caregiver.userId === req.user.id;
    const isAdmin = req.user.role === 'admin';
    
    if (!isCustomer && !isCaregiver && !isAdmin) {
      return next(new AppError('您没有权限查看此订单', 403));
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('获取订单信息错误:', error);
    return next(new AppError('获取订单信息失败', 500));
  }
};

// 创建新订单
exports.createOrder = async (req, res, next) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    const {
      pets,
      service,
      caregiver,
      startDateTime,
      endDateTime,
      address,
      specialInstructions,
      isRecurring,
      recurringPattern
    } = req.body;
    
    // 验证宠物是否属于当前用户
    const userPets = await Pet.find({
      _id: { $in: pets },
      owner: req.user.id
    });
    
    if (userPets.length !== pets.length) {
      return next(new AppError('您只能为自己的宠物创建订单', 400));
    }
    
    // 验证服务是否存在
    const serviceDoc = await Service.findById(service);
    if (!serviceDoc) {
      return next(new AppError('服务不存在', 404));
    }
    
    // 验证护理员是否存在和可用
    const caregiverDoc = await Caregiver.findById(caregiver);
    if (!caregiverDoc) {
      return next(new AppError('护理员不存在', 404));
    }
    
    if (caregiverDoc.status !== 'active') {
      return next(new AppError('护理员当前不可用', 400));
    }
    
    // 检查护理员是否有时间冲突
    const conflictingOrders = await Order.find({
      caregiver: caregiver,
      status: { $in: ['pending', 'confirmed', 'in_progress'] },
      $or: [
        {
          startDateTime: { $lte: new Date(endDateTime) },
          endDateTime: { $gte: new Date(startDateTime) }
        }
      ]
    });
    
    if (conflictingOrders.length > 0) {
      return next(new AppError('护理员在此时间段已有其他订单', 400));
    }
    
    // 计算订单费用
    const duration = (new Date(endDateTime) - new Date(startDateTime)) / (1000 * 60 * 60); // 小时
    const baseFee = serviceDoc.pricing.basePrice * duration;
    const additionalPetFee = pets.length > 1 ? (pets.length - 1) * serviceDoc.pricing.additionalPetMultiplier * serviceDoc.pricing.basePrice : 0;
    
    // 检查是否为紧急服务或周末服务
    const isEmergency = (new Date(startDateTime) - new Date()) < 24 * 60 * 60 * 1000; // 24小时内
    const isWeekend = [0, 6].includes(new Date(startDateTime).getDay());
    
    let emergencyFee = 0;
    let weekendFee = 0;
    
    if (isEmergency && serviceDoc.pricing.emergencyMultiplier) {
      emergencyFee = baseFee * (serviceDoc.pricing.emergencyMultiplier - 1);
    }
    
    if (isWeekend && serviceDoc.pricing.weekendMultiplier) {
      weekendFee = baseFee * (serviceDoc.pricing.weekendMultiplier - 1);
    }
    
    const totalAmount = baseFee + additionalPetFee + emergencyFee + weekendFee;
    
    // 创建订单
    const orderData = {
      customer: req.user.id,
      caregiver,
      pets,
      service,
      serviceDetails: {
        type: serviceDoc.category,
        title: serviceDoc.name,
        description: serviceDoc.description,
        specialInstructions
      },
      schedule: {
        startDateTime: new Date(startDateTime),
        endDateTime: new Date(endDateTime),
        duration,
        isRecurring,
        recurringPattern
      },
      address,
      pricing: {
        baseFee,
        additionalFees: [
          ...(additionalPetFee > 0 ? [{ type: 'additional_pets', amount: additionalPetFee, description: `额外宠物费用 (${pets.length - 1}只)` }] : []),
          ...(emergencyFee > 0 ? [{ type: 'emergency', amount: emergencyFee, description: '紧急服务费' }] : []),
          ...(weekendFee > 0 ? [{ type: 'weekend', amount: weekendFee, description: '周末服务费' }] : [])
        ],
        totalAmount,
        currency: 'CNY'
      },
      status: 'pending'
    };
    
    const newOrder = await Order.create(orderData);
    
    // 填充关联数据
    await newOrder.populate([
      { path: 'customer', select: 'firstName lastName email phone' },
      { path: 'caregiver', select: 'user experience rating' },
      { path: 'pets', select: 'name species breed photos' },
      { path: 'service', select: 'name category duration pricing' }
    ]);
    
    logger.info(`新订单创建: ${req.user.email} - 订单号: ${newOrder.orderNumber}`);
    
    // TODO: 发送通知给护理员
    
    res.status(201).json({
      status: 'success',
      message: '订单创建成功',
      data: {
        order: newOrder
      }
    });
  } catch (error) {
    logger.error('创建订单错误:', error);
    return next(new AppError('创建订单失败', 500));
  }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res, next) => {
  try {
    const { status, reason } = req.body;
    
    if (!status) {
      return next(new AppError('请提供订单状态', 400));
    }
    
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    // 检查权限
    const isCustomer = order.customer.toString() === req.user.id;
    const isCaregiver = order.caregiver && order.caregiver.toString() === req.user.id;
    const isAdmin = req.user.role === 'admin';
    
    if (!isCustomer && !isCaregiver && !isAdmin) {
      return next(new AppError('您没有权限更新此订单状态', 403));
    }
    
    // 验证状态转换的合法性
    const validTransitions = {
      pending: ['confirmed', 'cancelled'],
      confirmed: ['in_progress', 'cancelled'],
      in_progress: ['completed', 'cancelled'],
      completed: [],
      cancelled: []
    };
    
    if (!validTransitions[order.status].includes(status)) {
      return next(new AppError(`无法从 ${order.status} 状态转换到 ${status} 状态`, 400));
    }
    
    // 根据角色限制状态更新权限
    if (isCustomer && !['cancelled'].includes(status)) {
      return next(new AppError('客户只能取消订单', 403));
    }
    
    if (isCaregiver && !['confirmed', 'in_progress', 'completed'].includes(status)) {
      return next(new AppError('护理员无法设置此状态', 403));
    }
    
    // 更新订单状态
    await order.updateStatus(status, reason, req.user.id);
    
    logger.info(`订单状态更新: ${order.orderNumber} - ${order.status} -> ${status}`);
    
    // TODO: 发送状态更新通知
    
    res.status(200).json({
      status: 'success',
      message: '订单状态更新成功',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('更新订单状态错误:', error);
    return next(new AppError('更新订单状态失败', 500));
  }
};

// 取消订单
exports.cancelOrder = async (req, res, next) => {
  try {
    const { reason } = req.body;
    
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    // 检查权限
    const isCustomer = order.customer.toString() === req.user.id;
    const isCaregiver = order.caregiver && order.caregiver.toString() === req.user.id;
    const isAdmin = req.user.role === 'admin';
    
    if (!isCustomer && !isCaregiver && !isAdmin) {
      return next(new AppError('您没有权限取消此订单', 403));
    }
    
    // 检查是否可以取消
    if (!order.canCancel) {
      return next(new AppError('此订单无法取消', 400));
    }
    
    // 取消订单
    await order.cancelOrder(reason, req.user.id);
    
    logger.info(`订单取消: ${order.orderNumber} - 原因: ${reason}`);
    
    // TODO: 处理退款逻辑
    // TODO: 发送取消通知
    
    res.status(200).json({
      status: 'success',
      message: '订单取消成功',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('取消订单错误:', error);
    return next(new AppError('取消订单失败', 500));
  }
};

// 开始服务
exports.startService = async (req, res, next) => {
  try {
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    // 只有护理员可以开始服务
    const caregiver = await Caregiver.findOne({ user: req.user.id });
    if (!caregiver || order.caregiver.toString() !== caregiver._id.toString()) {
      return next(new AppError('只有指定的护理员可以开始服务', 403));
    }
    
    if (order.status !== 'confirmed') {
      return next(new AppError('只有已确认的订单可以开始服务', 400));
    }
    
    // 开始服务
    await order.startService();
    
    logger.info(`服务开始: ${order.orderNumber}`);
    
    // TODO: 发送服务开始通知给客户
    
    res.status(200).json({
      status: 'success',
      message: '服务已开始',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('开始服务错误:', error);
    return next(new AppError('开始服务失败', 500));
  }
};

// 完成服务
exports.completeService = async (req, res, next) => {
  try {
    const { report } = req.body;
    
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    // 只有护理员可以完成服务
    const caregiver = await Caregiver.findOne({ user: req.user.id });
    if (!caregiver || order.caregiver.toString() !== caregiver._id.toString()) {
      return next(new AppError('只有指定的护理员可以完成服务', 403));
    }
    
    if (order.status !== 'in_progress') {
      return next(new AppError('只有进行中的订单可以完成服务', 400));
    }
    
    // 完成服务
    await order.completeService(report);
    
    logger.info(`服务完成: ${order.orderNumber}`);
    
    // TODO: 发送服务完成通知给客户
    // TODO: 处理付款
    
    res.status(200).json({
      status: 'success',
      message: '服务已完成',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('完成服务错误:', error);
    return next(new AppError('完成服务失败', 500));
  }
};

// 添加评价
exports.addReview = async (req, res, next) => {
  try {
    const { rating, comment, reviewType } = req.body; // reviewType: 'customer' or 'caregiver'
    
    if (!rating || !reviewType) {
      return next(new AppError('请提供评分和评价类型', 400));
    }
    
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return next(new AppError('未找到该订单', 404));
    }
    
    if (order.status !== 'completed') {
      return next(new AppError('只有已完成的订单可以评价', 400));
    }
    
    // 检查权限和评价类型
    const isCustomer = order.customer.toString() === req.user.id;
    const isCaregiver = order.caregiver && order.caregiver.toString() === req.user.id;
    
    if (reviewType === 'customer' && !isCustomer) {
      return next(new AppError('只有客户可以评价护理员', 403));
    }
    
    if (reviewType === 'caregiver' && !isCaregiver) {
      return next(new AppError('只有护理员可以评价客户', 403));
    }
    
    // 添加评价
    await order.addReview(reviewType, {
      rating,
      comment,
      reviewer: req.user.id
    });
    
    logger.info(`订单评价: ${order.orderNumber} - ${reviewType} 评价`);
    
    res.status(200).json({
      status: 'success',
      message: '评价添加成功',
      data: {
        order
      }
    });
  } catch (error) {
    logger.error('添加评价错误:', error);
    return next(new AppError('添加评价失败', 500));
  }
};

// 获取订单统计信息
exports.getOrderStats = async (req, res, next) => {
  try {
    const stats = await Order.aggregate([
      {
        $group: {
          _id: null,
          totalOrders: { $sum: 1 },
          pendingOrders: {
            $sum: {
              $cond: [{ $eq: ['$status', 'pending'] }, 1, 0]
            }
          },
          confirmedOrders: {
            $sum: {
              $cond: [{ $eq: ['$status', 'confirmed'] }, 1, 0]
            }
          },
          inProgressOrders: {
            $sum: {
              $cond: [{ $eq: ['$status', 'in_progress'] }, 1, 0]
            }
          },
          completedOrders: {
            $sum: {
              $cond: [{ $eq: ['$status', 'completed'] }, 1, 0]
            }
          },
          cancelledOrders: {
            $sum: {
              $cond: [{ $eq: ['$status', 'cancelled'] }, 1, 0]
            }
          },
          totalRevenue: {
            $sum: {
              $cond: [
                { $eq: ['$status', 'completed'] },
                '$pricing.totalAmount',
                0
              ]
            }
          }
        }
      }
    ]);
    
    // 按月统计订单数量
    const monthlyStats = await Order.aggregate([
      {
        $group: {
          _id: {
            year: { $year: '$createdAt' },
            month: { $month: '$createdAt' }
          },
          count: { $sum: 1 },
          revenue: {
            $sum: {
              $cond: [
                { $eq: ['$status', 'completed'] },
                '$pricing.totalAmount',
                0
              ]
            }
          }
        }
      },
      { $sort: { '_id.year': -1, '_id.month': -1 } },
      { $limit: 12 }
    ]);
    
    res.status(200).json({
      status: 'success',
      data: {
        overview: stats[0] || {
          totalOrders: 0,
          pendingOrders: 0,
          confirmedOrders: 0,
          inProgressOrders: 0,
          completedOrders: 0,
          cancelledOrders: 0,
          totalRevenue: 0
        },
        monthlyStats
      }
    });
  } catch (error) {
    logger.error('获取订单统计错误:', error);
    return next(new AppError('获取统计信息失败', 500));
  }
};